package com.sfh.appversion.base;


import com.sfh.appversion.base.errorcode.BaseErrorCode;
import com.sfh.appversion.base.exception.AbstractException;

import java.io.Serializable;
import java.util.Optional;

/**
 * 如
 * {"data":这里是你要返回的数据类型,
 * "status":1,
 * "successed": true,
 * "message":"操作成功"}
 */
public class Result<T> implements Serializable{

    private String code;
    private String msg;
    private T data;
    protected Result() {
        this.code = "0";
    }
    protected Result(String code) {
        this.code = code;
    }

    protected Result(String status, T data) {
        this.code = status;
        this.data = data;
    }

    protected Result(String code, String message, T data) {
        this.code = code;
        this.msg = message;
        this.data = data;
    }

    protected Result(String code, String message) {
        this.code = code;
        this.msg = message;
    }


    public Result setCode(String code) {
        this.code = code;
        return this;
    }

    public void setData(T data) {
        this.data = data;
    }


    public String getCode() {
        return code;
    }

    public T getData() {
        return data;
    }

    public static <T> Result<T> success(String msg) {
        return new Result<T>("200", msg);
    }

    public static <T> Result<T> success(T data) {
        return new Result<T>("200","操作成功", data);
    }

    public static <T> Result<T> create(String code, String message) {
        return new Result<T>(code, message);
    }

    public static <T> Result<T> create(String code, String message, T data) {
        return new Result<T>(code, message, data);
    }

    /**
     * 构建服务端失败响应
     */
    public static Result<Void> failure() {
        return Result.create(BaseErrorCode.SERVICE_ERROR.code(),BaseErrorCode.SERVICE_ERROR.msg());
    }

    /**
     * 通过 {@link AbstractException} 构建失败响应
     */
    public static Result failure(AbstractException abstractException) {
        String errorCode = Optional.ofNullable(abstractException.getCode())
                .orElse(BaseErrorCode.SERVICE_ERROR.code());
        String errorMessage = Optional.ofNullable(abstractException.getMessage())
                .orElse(BaseErrorCode.SERVICE_ERROR.msg());
        return Result.create(errorCode,errorMessage);
    }

    /**
     * 通过 errorCode、errorMessage 构建失败响应
     */
    public static Result<Void> failure(String errorCode, String errorMessage) {
        return Result.create(errorCode,errorMessage);
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }
}

